﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Transfer;
using BranchOfSansar.Register.Reports.Forms;
using System.Drawing.Printing;

namespace BranchOfSansar.Register.Trans
{
    public partial class frmTransExtend : BranchOfSansar.Register.Trans.frmTransBase
    {

        #region Form Load
        public frmTransExtend()
        {
            InitializeComponent();
        }

        public frmTransExtend(long cont_no):this()
        {
            txtContractNo.Text = cont_no.ToString();
            SetContractNo(cont_no);       
        }

        private void frmTransExtend_ContractSelected()
        {
            pnlTransfer.Enabled = true;                        
            txtProdCode.Text = Contract.CurrProdCode.ToString();
            loadContractVal();
        }

        private void frmTransExtend_Load(object sender, EventArgs e)
        {
            txtDate.DateTime = Globals.SystemDate;
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new BranchOfSansar.Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                txtProdCode.Properties.ValueMember = "ProdCode";
                txtProdCode.Properties.DisplayMember = "ProdCode";
                txtProdCode.Properties.DataSource = tc.Products("F");
            }
        }
        #endregion

        private void txtProdCode_EditValueChanged(object sender, EventArgs e)
        {
            loadContractVal();

        }
        private void loadContractVal()
        {
            using (BranchOfSansar.Sansar.Transfer.TransferClient tr = new Sansar.Transfer.TransferClient(Globals.Token))
            {
                BranchOfSansar.Sansar.Enquiry.Product p = (BranchOfSansar.Sansar.Enquiry.Product)txtProdCode.Properties.GetDataSourceRowByDisplayValue(txtProdCode.Text);
                if (p == null) return;
                txtPrice.Text = p.Price.ToString("#,##0");
                lblMonth.Text = string.Format("Сараар({0})", p.Length);

                txtPriceOfDay.Text = p.Length == 0 ? "0" : (p.Price / (30 * p.Length)).ToString("#,##0");
                txtProdDescription.Text = string.Format("{0}, {1}, {2} сар", p.Name, p.ProdType == "L" ? "Дараа" : "Урьдчилсан", p.Length);

                txtStartDate.DateTime = (DateTime)(DateTime.Now.CompareTo(Contract.EndDate) > 0 ? DateTime.Now : Contract.EndDate);
                txtEndDate.DateTime = txtStartDate.DateTime.AddMonths(p.Length);
            }
        }

        private void TxtEditValueChanged(object sender, EventArgs e)
        {
            txtTotalPrice.Text = (decimal.Parse(txtPrice.Text) * txtQuantity.Value).ToString("#,##0");
            txtTotalPriceOfDay.Text = (decimal.Parse(txtPriceOfDay.Text) * txtQuantityOfDay.Value).ToString("#,##0");
            txtAmount.Value = decimal.Parse(txtTotalPrice.Text) + decimal.Parse(txtTotalPriceOfDay.Text);
            txtPaidAmount.Value = txtAmount.Value;
            txtEndDate.DateTime = txtStartDate.DateTime.AddMonths((int)txtQuantity.Value).AddDays((int)txtQuantityOfDay.Value);
        }

        private void TxtBalanceValueChanged(object sender, EventArgs e)
        {
            txtLast.Text = (Contract.Balance + txtAmount.Value - txtPaidAmount.Value).ToString("#,##0");         
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            BranchOfSansar.Sansar.Enquiry.Product p = (BranchOfSansar.Sansar.Enquiry.Product)txtProdCode.Properties.GetDataSourceRowByDisplayValue(txtProdCode.Text);
            if (p == null)
            {
                Globals.Warr("Сунгах бүтээгдэхүүн сонгоогүй байна.");
                return;
            }
            List<Transaction> txn = new List<Transaction>();
            SendContract con = new SendContract()
            {
                ContractNo = Contract.ContractNo,
                Balance = decimal.Parse(txtLast.Text),
                CurrProdCode = p.ProdCode,
                EndDate = txtEndDate.DateTime,
                StartDate = txtStartDate.DateTime
            };
            decimal paid = txtPaidAmount.Value;
            decimal bal = decimal.Parse(txtBalance.Text);


            //Сараар хийсэн төлбөр
            decimal month_amount=decimal.Parse(txtTotalPrice.Text);
            if (txtQuantity.Value > 0)
            {
                txn.Add(new Transaction()
                {
                    ContractNo = Contract.ContractNo,
                    ProdCode = p.ProdCode,
                    Quantity = (int)txtQuantity.Value,
                    StartDate = txtStartDate.DateTime,
                    EndDate = txtStartDate.DateTime.AddMonths((int)txtQuantity.Value),
                    Status = 1,
                    TxnCategory = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbTransCategory.SelectedItem).StrValue,
                    BankNo = cmbBank.Enabled ? ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbBank.SelectedItem).IntValue : 0,
                    TxnPrice = decimal.Parse(txtPrice.Text),
                    TxnFirstBalance = bal,
                    TxnDebtAmount = month_amount,
                    TxnDate = txtDate.DateTime,
                    TxnDesc = txtDesc.Text.Length > 0 ? txtDesc.Text : "Сарын төлбөр",
                    TxnType = 1200,
                    UserNo = Globals.UserId
                });
                txn[0].TxnAmount = paid > month_amount ? month_amount : paid;
                paid = paid > month_amount ? paid - month_amount : 0;
                bal = bal + month_amount - txn[0].TxnAmount;
            }
            
            
            //Хоногоор төлбөр хийсэн бол.
            decimal day_amount= decimal.Parse(txtTotalPriceOfDay.Text);
            if (txtQuantityOfDay.Value > 0)
            {
                txn.Add(new Transaction()
                {
                    ContractNo = Contract.ContractNo,
                    ProdCode = p.ProdCode,
                    Quantity = (int)txtQuantityOfDay.Value,
                    StartDate = txtEndDate.DateTime.AddDays((int)txtQuantityOfDay.Value * -1),
                    EndDate = txtEndDate.DateTime,
                    Status = 1,
                    TxnCategory = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbTransCategory.SelectedItem).StrValue,
                    BankNo = cmbBank.Enabled ? ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbBank.SelectedItem).IntValue : 0,
                    TxnPrice = decimal.Parse(txtPriceOfDay.Text),
                    TxnFirstBalance=bal,
                    TxnDebtAmount = day_amount,
                    TxnDate = txtDate.DateTime,
                    TxnDesc = txtDesc.Text.Length > 0 ? txtDesc.Text : "Өдөрийн төлбөр",
                    TxnType = 1201,
                    UserNo = Globals.UserId
                });
                txn[txn.Count-1].TxnAmount = paid > day_amount ? day_amount : paid;
                paid = paid > day_amount ? paid - day_amount : 0;                 
            }

             

            //Үлдэгдэл төлсөн бол.
            if (paid > 0)
            {
                txn.Add(new Transaction()
                {
                    ContractNo = Contract.ContractNo,
                    Quantity = 1,
                    Status = 1,
                    TxnCategory = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbTransCategory.SelectedItem).StrValue,
                    BankNo = cmbBank.Enabled ? ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbBank.SelectedItem).IntValue : 0,
                    TxnPrice = paid,
                    TxnFirstBalance=bal,
                    TxnDebtAmount=0,
                    TxnAmount = paid,
                    TxnDate = txtDate.DateTime,
                    TxnDesc =string.Format("({0}) {1}",con.Balance<0?"Илүү төлөлт":"Үлдэгдэлээс төлсөн",txtDesc.Text),
                    TxnType = 1203,
                    UserNo = Globals.UserId
                });
            }

            using (TransferClient tc = new TransferClient(Globals.Token))
            {
                var res = tc.DoTransaction(txn.ToArray(),new SendTransfer[]{}, con);
                if (res.Code != 0)
                    Globals.Warr(res.Message);
                else
                {
                    Globals.Info(res.Message);
                    this.JrNo = long.Parse(res.RetData.ToString());
                    if(PrintReceipt()==System.Windows.Forms.DialogResult.Cancel)
                    {
                       this.DialogResult = System.Windows.Forms.DialogResult.OK;
                       this.Close();
                    }
                }
            }
        }

        private void txtPaid_EditValueChanged(object sender, EventArgs e)
        {
            txtResult.Value = txtPaid.Value - txtAmount.Value;
        }

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void txtContractNo_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtStartDate_EditValueChanged(object sender, EventArgs e)
        {
            txtTotalPrice.Text = (decimal.Parse(txtPrice.Text) * txtQuantity.Value).ToString("#,##0");
            txtTotalPriceOfDay.Text = (decimal.Parse(txtPriceOfDay.Text) * txtQuantityOfDay.Value).ToString("#,##0");
            txtAmount.Value = decimal.Parse(txtTotalPrice.Text) + decimal.Parse(txtTotalPriceOfDay.Text);
            txtPaidAmount.Value = txtAmount.Value;
            txtEndDate.DateTime = txtStartDate.DateTime.AddMonths((int)txtQuantity.Value).AddDays((int)txtQuantityOfDay.Value);
        }

        private void txtBalance_EditValueChanged(object sender, EventArgs e)
        {

        }

     
    }
}
